import { Button } from 'antd-mobile';

const JsErrorDemo = () => {
	const triggerReferenceError = () => {
		console.log(user); // ReferenceError: user is not defined
	};

	const triggerTypeError = () => {
		// 场景1：访问null/undefined属性
		const user = null;
		console.log(user.name); // TypeError: Cannot read properties of null

		// 场景2：非函数调用
		const config = { debug: true };
		config.debug(); // TypeError: config.debug is not a function

		// 场景3：非法操作
		const obj = Object.freeze({ prop: 42 });
		obj.prop = 100; // TypeError: Cannot assign to read only property
	};

	const triggerRangeError = () => {
		// 递归栈溢出
		function stackOverflow() {
			stackOverflow();
		}
		stackOverflow();

		// 非法数组长度
		const arr = new Array(-1); // RangeError: Invalid array length

		// 数字转换异常
		const bigNum = 10n;
		Number(bigNum); // RangeError in some environments
	};

	const triggerAsyncError = () => {
		try {
			setTimeout(() => {
				try {
					console.log(a.x);
				} catch (error) {
					console.error('Async Error:', error);
				}
			}, 0);
		} catch (error) {
			console.log(error);
		}
	};

	return (
		<div
			style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}
		>
			<Button color='primary' size='middle' onClick={triggerReferenceError}>
				未定义变量
			</Button>

			<Button color='primary' size='middle' onClick={triggerTypeError}>
				类型错误
			</Button>

			<Button color='primary' size='middle' onClick={triggerRangeError}>
				范围错误
			</Button>

			<Button color='primary' size='middle' onClick={triggerAsyncError}>
				异步异常
			</Button>
		</div>
	);
};

export default JsErrorDemo;
